package com.simtop.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.simtop.common.ServerResponse;
import com.simtop.dao.UserDao;
import com.simtop.pojo.User;
import com.simtop.pojo.wddata.*;
import com.simtop.service.ApiService;
import com.simtop.service.LayOutService;
import com.simtop.util.JwtUtil;
import com.simtop.util.SHA256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/groupby")
@CrossOrigin
public class GroupByController {

    @Autowired
    private UserDao userDao;
    @Autowired
    private LayOutService layOutService;
    @Autowired
    private ApiService apiService;

    @PostMapping("/findGroupBy")
    public ServerResponse findGroupBy(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String groupId = jsonObject.getString("groupId");
            List<GroupUp> finAllGroupUp = apiService.finAllGroupUp(groupId);
            return ServerResponse.createBySuccess(finAllGroupUp);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByError();
        }

    }

    @PostMapping("/findGroupUserBy")
    public ServerResponse findGroupUserBy(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            //先拿到唯一id 的 子类
            Integer id = jsonObject.getInteger("id");
            wduserGroupByDao  wdwd = apiService.finOnewdGroupById(id);
            //
            String groupChead = wdwd.getGroupChead();
            //找到所有用户是
            List<User> wdwdwd =  apiService.findAllUser(groupChead);

            return ServerResponse.createBySuccess(wdwdwd);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByError();
        }

    }

    @PostMapping("/findAllGroupBy")
    public ServerResponse findAllGroupBy(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            List<GroupType> groupType = apiService.groupType();
            //
            for (GroupType asa:groupType
                 ) {
                int id = asa.getId();
                List<Integer>  tt = apiService.finByid(id);
                asa.setIds(tt);
            }



            return ServerResponse.createBySuccess(groupType);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByError();
        }

    }


    @PostMapping("/findAllUserBy")
    public ServerResponse findAllUserBy(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            //List<GroupType> groupType = apiService.groupTypeUser();
            List<wduserGroupBy> wdOne=apiService.findAllGroupByid();
            List<wduserGroupBy> wdTwo=apiService.findAllGroupByid2();
            newTsVo newTsVo = new  newTsVo();
            newTsVo.setGroupOne(wdOne);
            newTsVo.setGroupTwo(wdTwo);


            return ServerResponse.createBySuccess(newTsVo);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByError();
        }

    }

    @PostMapping("/insertGroupBy")
    public ServerResponse findAllLayOut(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject = JSONObject.parseObject(data);
            String groupName = jsonObject.getString("groupName");
            JSONArray id = jsonObject.getJSONArray("id");
            //拿到分组name保存
            //如果查到一样的name就不保存
            int is  = apiService.finOnly(groupName);
       if(is == 0) {
    apiService.insertGroupType(groupName);
     }
            //找到类型唯一id
            int findOneTypeId = apiService.findOneTypeId(groupName);
           // System.out.println(findOneTypeId);
            Iterator<Object> iterator = id.stream().iterator();
            while (iterator.hasNext()) {
                Object next = iterator.next();
                Integer i = (Integer) next;
                //根据id找到 设备名称 和 设备编号 和设备类型
               MainTain  findBynameAndidAndType= apiService.findBynameAndidAndType(i);

               String deviceName = findBynameAndidAndType.getDeviceName();
               Integer deviceId =  findBynameAndidAndType.getDeviceId();
               String testType =  findBynameAndidAndType.getTestType();


               //保存分组表
                apiService.insertGroupBy(groupName,i,deviceName,deviceId,testType,findOneTypeId);


                // apiService.finOne
                    }

            return ServerResponse.createBySuccess();


        }catch (Exception e){
            e.printStackTrace();

            return ServerResponse.createByError();
        }

    }


    //添加分组 用户

    @PostMapping("/insertGroupUsersBy")
    public ServerResponse insertGroupUsersBy(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject = JSONObject.parseObject(data);
            String types = jsonObject.getString("type");
            String name = jsonObject.getString("name");
            apiService.insertGroupbubu(types,name);



            return ServerResponse.createBySuccess();


        }catch (Exception e){
            e.printStackTrace();

            return ServerResponse.createByError();
        }

    }


    //添加分组 用户

    @PostMapping("/seepassword")
    public ServerResponse seepassword(@RequestBody String data,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            User s = new User();
             s=userDao.findById(u.getId());
            JSONObject jsonObject = JSONObject.parseObject(data);
            String newpassword = jsonObject.getString("newpassword");
        //    System.out.println(u.getId());
            String s1 = SHA256Util.generateShaPwd(newpassword);
            if(s.getPassword().equals(s1)){
            //密码一样 通过!!!
                return ServerResponse.createBySuccess("密码一致");
            }else {
                return ServerResponse.createByErrorMsg("密码错误");
            }



        }catch (Exception e){
            e.printStackTrace();

            return ServerResponse.createByError();
        }

    }



    @PostMapping("/insertGroupUserBy")
    public ServerResponse insertGroupUserBy(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{

            JSONObject jsonObject = JSONObject.parseObject(data);
            String groupName = jsonObject.getString("groupName");
            JSONArray id = jsonObject.getJSONArray("id");



            return ServerResponse.createBySuccess();
/*            //拿到分组name保存
            //如果查到一样的name就不保存
            int is  = apiService.finOnly1(groupName);
            if(is == 0) {
                apiService.insertGroupType1(groupName);
            }
            //找到类型唯一id
            int findOneTypeId = apiService.findOneTypeId1(groupName);
            System.out.println(findOneTypeId);
            Iterator<Object> iterator = id.stream().iterator();
            while (iterator.hasNext()) {
                Object next = iterator.next();
                Integer i = (Integer) next;
                //根据用户id找到 用户表
                UserVo us = apiService.findOne(i);
                String name = us.getName();
                String rolename = us.getRolename();


                apiService.insertGroupBy1(i,name,rolename,findOneTypeId);

            }*/





        }catch (Exception e){
            e.printStackTrace();

            return ServerResponse.createByError();
        }

    }

    @PostMapping("deleteGroupById")
    @ResponseBody
    public ServerResponse deleteGroupById(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }

        try {

            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer id = jsonObject.getInteger("id");
            layOutService.deleteGroupById(id);
            layOutService.deleteGroup(id);

            return ServerResponse.createBySuccess();


        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }


    }

    @PostMapping("deleteGroupUserById")
    @ResponseBody
    public ServerResponse deleteGroupUserById(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }

        try {
            //如果本人的分组id  照应 就返回不对!!
            Integer ids = u.getId();
         //   System.out.println(ids);
            //找到group one
            Integer lastGroup  = apiService.lastGroup(ids);


            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer id = jsonObject.getInteger("id");
            String type = jsonObject.getString("type");

            if(lastGroup == id){
                //该用户 用到分组了
                return ServerResponse.createByErrorMsg("该分组下有用户，无法删除");
            }

            apiService.deletOne(id , type);
            return ServerResponse.createBySuccess();


        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }


    }

    @PostMapping("/updategroupBy")
    public ServerResponse updategroupBy(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{

            JSONObject jsonObject = JSONObject.parseObject(data);
            String groupName = jsonObject.getString("name");
            Integer groupid = jsonObject.getInteger("groupid");
            JSONArray id = jsonObject.getJSONArray("id");
            //删除所有的信息
            apiService.deleteGroup(groupid);
            //先去修改所有的groupName

            apiService.updateAllGroupName(groupName,groupid);
            //分组表修改name
            apiService.updateAllgoup(groupName,groupid);

            //拿到分组name保存

            Iterator<Object> iterator = id.stream().iterator();
            while (iterator.hasNext()) {
                Object next = iterator.next();
                Integer i = (Integer) next;

                //根据id找到 设备名称 和 设备编号 和设备类型
                MainTain  findBynameAndidAndType= apiService.findBynameAndidAndType(i);

                String deviceName = findBynameAndidAndType.getDeviceName();
                Integer deviceId =  findBynameAndidAndType.getDeviceId();
                String testType =  findBynameAndidAndType.getTestType();


                //保存分组表
                apiService.insertGroupBy(groupName,i,deviceName,deviceId,testType,groupid);


                // apiService.finOne
            }

            return ServerResponse.createBySuccess();


        }catch (Exception e){
            e.printStackTrace();

            return ServerResponse.createByError();
        }

    }


    //编辑 用户分组
    @PostMapping("/updategroupuserBy")
    public ServerResponse updategroupuserBy(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{

            JSONObject jsonObject = JSONObject.parseObject(data);
            String types = jsonObject.getString("type");
            Integer id = jsonObject.getInteger("id");
            String  name = jsonObject.getString("name");

            if(types.equals("分组1")){
                //拿到 原来值
                String groupchead = apiService.findOneGroupByOne(id);
             //   System.out.println(groupchead);
                apiService.cheageUser(groupchead,name);

            }

            if(types.equals("分组2")){
                //拿到 原来值
             //   String as = apiService.findOneGroupByOne();
                String groupchead = apiService.findOneGroupByOne2(id);
            //    System.out.println(groupchead);
                apiService.cheageUser2(groupchead,name);

            }


            apiService.updateAllgroupByid(types,id,name);



            return ServerResponse.createBySuccess();


        }catch (Exception e){
            e.printStackTrace();

            return ServerResponse.createByError();
        }

    }

}
